package internal

import (
	"encoding/json"
	"fmt"
	"reflect"
	"GoServer/database"
	"GoServer/msg"
	"GoServer/msgbackend"
	"GoServer/user"
	"github.com/name5566/leaf/gate"
	"github.com/name5566/leaf/log"
)

//消息接收

func init() {
	// 向当前模块（game 模块）注册 Hello 消息的消息处理函数 handleHello
	handler(&msg.Message{}, handleHello)
}

func handler(m interface{}, h interface{}) {
	skeleton.RegisterChanRPC(reflect.TypeOf(m), h)
}

func handleHello(args []interface{}) {
	m := args[0].(*msg.Message)
	// fmt.Println(m.MsgType)
	// 消息的发送者
	a := args[1].(gate.Agent)

	// 输出收到的消息的内容
	// log.Debug("hello %v", m.Authkey)
	log.Debug("send user1 %v", a.LocalAddr())
	// var f interface{}
	// json.Unmarshal([]byte(a), f)
	//fmt.Println(typeof(a))
	g_JsonConfig := database.G_JsonConfig
	ToserverTopic := g_JsonConfig.PrivatetopicAll.Gategetserver
	Angets := user.GetSocketUser(a)
	//消息限流阻断
	// res := user.UserInfoCacheGet(m.Loginname)
	// Lb := res.Lb
	// if !Lb.Access() {
	// 	fmt.Println(Lb)
	// }
	// if !Lb.Access() {
	// // 给发送者回应一个消息
	// a.WriteMsg(&msg.Respose{
	// 	Result: "Access fail",
	// })
	// } else {
		mapMsg := make(map[string]interface{})
		mapMsg["MsgType"] = m.MsgType
		mapMsg["MsgData"] = m.MsgValue
		//mapMsg["userName"] = m.Loginname
		mapMsg["userName"] =  Angets
		getTime := msgbackend.GetTime()
		mapMsg["SendTime"] = getTime
		mapMsg["Sender"] = ToserverTopic

		jsonBytes, err := json.Marshal(&mapMsg)
		if err != nil {

		} else {
			// fmt.Println(jsonBytes)
			log.Debug("c2s %v",jsonBytes)
			msgbackend.MsgRouterWriter(string(jsonBytes))
		}
	// }

}

func typeof(v interface{}) string {
	return fmt.Sprintf("%T", v)
}

//测试消息广播
func Ratiate() {
	for a := range agentsAll {
		fmt.Println(a.LocalAddr())
		a.WriteMsg(&msg.Respose{
			Result: "success client",
		})
	}
}
